package com.dries.portal.module.coupon.executor.impl;

import com.dries.portal.module.coupon.enums.RuleFlag;
import com.dries.portal.module.coupon.executor.AbstractExecutor;
import com.dries.portal.module.coupon.executor.RuleExecutor;
import com.dries.portal.module.coupon.vo.CouponTemplateSDK;
import com.dries.portal.module.coupon.vo.SettlementInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Description: 满减优惠券结算规则执行器
 * @Author ZSY
 * @createTime 2020/7/31 16:31
 */
@Slf4j
@Component
public class ManJianExecutor extends AbstractExecutor implements RuleExecutor {


    /**
     * 规则标记类型
     *
     * @return
     */
    @Override
    public RuleFlag ruleConfig() {
        return RuleFlag.MANJAIN;
    }

    /**
     * 优惠券规则的计算
     *
     * @param settlement
     */
    @Override
    public SettlementInfo computeRule(SettlementInfo settlement) {

        BigDecimal goodsSum = retain2BigDecimals(goodsCostSum(settlement.getGoodsInfos()));
        SettlementInfo probability = processGoodsTypeNotSatisfy(
                settlement, goodsSum
        );

        if (probability != null) {
            log.info("满减券与商品类型不匹配");
            return probability;
        }

        // 判断满减是否符合折扣标准
        SettlementInfo info = checkBase(goodsSum, settlement);
        if (info != null) {
            return info;
        } else {
            CouponTemplateSDK sdk = settlement.getCouponAndTemplateInfos().get(0).getTemplate();
            // 额度
            BigDecimal quota = sdk.getRule().getDiscount().getQuota();
            // 计算使用优惠券之后的价格 - 结算
            settlement.setCost(retain2BigDecimals(
                    (goodsSum.subtract(quota)).compareTo(minCostBigDecimal()) > 0
                            ? goodsSum.subtract(quota) : minCostBigDecimal() ));

            log.info("使用满减券之前需要花费的金额：{}，实际支付的金额：{}", goodsSum.toString(), settlement.getCost().toString());

            return settlement;
        }

    }
}
